<template>
    <div class = 'followEdit'>
        <h2 style="text-align:center;font-weight:600;margin-bottom:10px;color: #333">随访表单{{title}}</h2> 
        <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="75" label-position="left">
            <div class="main">
                <p class="title">基本信息</p>
                <Row gutter="64" class="box">
                    <Col span="16">
                        <FormItem label="随访表单名称：" prop="formName" :label-width="110">
                            <Input v-model="formValidate.formName" placeholder="请输入表单名称" style='width:100%;' :maxlength="32"></Input>
                        </FormItem>
                    </Col>
                    <Col span="8">
                        <FormItem label="表单类型：" prop="pattern" :label-width="85">
                            <Select v-model="formValidate.pattern" style="width:200px">
                                <Option v-for="(item, index) in formList" :value="item.id" :key="item.id" style='text-align:center;'>{{ item.name }}</Option>
                            </Select>
                        </FormItem>
                    </Col>
                    <Col span="8">
                        <FormItem label="适用科室：" prop="deptId" :label-width="85">
                            <Select v-model="formValidate.deptId" style="width:50%;">
                                <Option
                                    v-for="item in deptmentList"
                                    :value="item.id"
                                    :key="item.id"
                                    style='text-align:center'
                                >{{item.deptNickname}}</Option>
                            </Select>
                        </FormItem>
                    </Col>
                    <Col span="8">
                        <FormItem label="是否使用：">
                            <iSwitch size="large"  v-model="iused" style="margin-left:10px;" >
                                <span slot="open">开启</span>
                                <span slot="close">关闭</span>
                            </iSwitch>
                        </FormItem>
                    </Col>
                </Row>
            </div>
            <div class="main">
                <p class="title">详细内容</p>
                <Row  gutter="64" class="box">
                    <Col span="21">
                        <Table stripe :columns="columns1" :data="data1" ref="table1" style="margin:10px 0;">
                            <template slot="questionNumber" slot-scope="props" >
                                <InputNumber v-model="props.row.questionNumber" placeholder="请输入数字" :min='1' :max="10000"></InputNumber>   
                            </template>
                        </Table>
                    </Col>
                    <Col>
                        <Button type='info' @click="addAnswer(1,true)" style="margin:10px 0">
                            <i class = "iconfont icon-add" style="font-size:14px;margin-right:5px"></i>添加题目
                        </Button>
                    </Col>                   
                </Row>
            </div>
        </Form>
        <div style="margin: 20px 0;width:100%;text-align:center;">
            <Button type="primary" style="width:75px;height:35px;" @click="handleSubmit('formValidate')" :disabled='btndisabled'>
                <Icon type="ios-checkmark" style="margin-right: 5px" />保存
            </Button>
            <Button @click="handleReset('formValidate')" style="width:75px;height:35px;margin-left: 8px">
                <i class = "iconfont icon-butongyi" style="font-size:14px;margin-right:5px"></i>取消
            </Button>
        </div>
        <!-- 添加题目弹窗 -->
        <Modal
            v-model="addtitle"
            title="题目选择"            
            footer-hide           
            width='900'>
            <div class="ibanner_header">
                <div class="box">
                    <div class="header_input">
                    <Input
                        v-model.trim="val"
                        placeholder="请输入名称检索"
                        style="width: 200px;margin-right:10px;"
                        clearable
                    />
                    </div>
                    <Button type="primary" icon="ios-search" @click="loadingFollow(1,val)"></Button>
                </div>
            </div>    
            <Table stripe :columns="columns2" :data="data2" style="margin:10px 0;" highlight-row ref="table" >
                <template slot="flag" slot-scope="props" >
                    <Checkbox v-model="props.row.flag" @on-change="handleRowChange(props.row)"></Checkbox>                            
                </template>
            </Table>
            <Page :total="count" @on-change="pageChange" :current="pageNo" :page-size='pageSize' style='text-align:center;' />
            <div style="width:100%;text-align:center;margin-top:20px ">
                <Button type="primary" @click="add" class="s2">
                    <Icon type="ios-checkmark" style="margin-right: 5px" />确认
                </Button>
                <Button @click="cancelAddtitle" class="s2">
                    <i class = "iconfont icon-butongyi" style="font-size:14px;margin-right:5px"></i>取消
                </Button>
            </div>    
        </Modal>
        <!-- 查看详情弹窗 -->
        <Modal
            v-model="follow"
            title="题目信息"            
            footer-hide           
            width='600'
        >
            <div style="margin: 0 20px">
                <div class="arr">
                    <span class="s1">题目名称：</span>
                    <span class="s2">{{question}}</span>
                </div>
                <div class="arr">
                    <span class="s1">题目类型：</span>
                    <span class="s2">{{questionType}}</span>
                </div>
                <div class="arr">
                    <span class="s1"  v-if="questionType == '选择题加填空题' || questionType == '单项选择题' || questionType == '多项选择题' ">选项信息：</span>
                    <span class="s1" v-if="questionType == '问答题' ||  questionType == '宣教科普' ">答案信息：</span>
                    <span class="s2">{{option}}</span>
                </div>
                <div class="arr" v-if="questionType == '选择题加填空题' || questionType == '单项选择题' || questionType == '多项选择题' ">
                    <span class="s1">参考答案：</span>
                    <span class="s2">{{answer}}</span>
                </div>
                <div class="arr" v-if="questionType == '选择题加填空题' ">
                    <span class="s1">参考答案信息：</span>
                    <span class="s2">{{answerSelect}}</span>
                </div>
                <div style="width:100%;text-align:center;margin-top:20px ">
                    <Button @click="cancel" class="s2">
                        <i class = "iconfont icon-butongyi" style="font-size:14px;margin-right:5px"></i>取消
                    </Button>
                </div>
            </div>               
        </Modal>
    </div>
</template>
<script>
import api from "@/api/commonApi";
export default {
    data () {
        return {
            title: '新增',
            addtitle: false,
            follow: false,
            iused: false,
            deptType: "",
            deptName: "",
            deptId: "",
            deptmentList:[],
            pageNo: 1,
            pageSize: 10,
            count: 10,
            id: sessionStorage.getItem("hospitalId"),
            data1: [],
            columns1: [
                {
                    title:"排序",
                    key:'sum',
                    align:'center',
                    width: 100
                },
                {
                    title:"题目类型",
                    key:'questionType',
                    align:'center',
                    width: 200,
                    render:(h,params) => {
                        let row = params.row;
                        let type = this.followList[row.questionType - 1].name
                        return [
                            h('span', {
                            }, type)
                        ]
                    }
                },
                {
                    title:"题目名称",
                    key:'question',
                    align:'center'
                },               
                {
                    title:"显示顺序(必填)",
                    key:'questionNumber',
                    align:'center',
                    width: 150,
                    render:(h,params) => {
                        this.data1[params.index] = params.row
                        return [
                            h('div', 
                                this.$refs.table1.$scopedSlots.questionNumber({
                                    row: params.row,
                                    idx: params.row._index
                                   
                                })  
                            )
                        ]
                    }
                },
                {
                    title:"设置",
                    align:"center",
                    width: 200,
                    render: (h,params) => {
                        let row = params.row;
                        return [
                            h('Button',{
                                style: {
                                    background: "#fff",
                                    color: " #5362e1",
                                    borderRadius: "15px",
                                    border: "1px solid  #5362e1",
                                    width: "60px",
                                    marginRight:"10px"
                                },
                            on: {
                                click: () => {
                                  this.lookitem(row)                                
                                },
                            }
                        },'查看'),
                        h('Button',{
                            style: {
                                background: "#fff",
                                color: " #5362e1",
                                borderRadius: "15px",
                                border: "1px solid  #5362e1",
                                width: "60px",
                                marginRight:"10px"
                            },
                            on: {
                                click: () => {
                                    this.data1.splice(params.index, 1);
                                    this.data1.forEach((item,index)=>{
                                        item.questionNumber = index+1;
                                        item.sum = this.addZeros(index);
                                    })
                                }
                            }
                        },'删除')
                        ]
                    }
                }
            ],
            followList: [
                { name:'单项选择题',id:1 },
                { name:'选择题加填空题',id:2 },
                { name:'问答题',id:3 },
                { name:'多项选择题',id:4 },
                { name:'宣教科普',id:5 },
            ],
            formValidate: {
                pattern : "",
                formName : "",
                id: "",
                deptId: "",
            },
            ruleValidate: {
                formName: [{ required: true, message: '请输入表单名称', trigger: 'blur' }],
                pattern: [{ required: true, message: '请选择表单类型', trigger: 'change'}],
                deptId: [{ required: true, message: '请选择科室', trigger: 'change'}],
            },
            formId: '',
            question: '',
            questionType: '',
            option: '',
            answer: '',
            answerSelect: '',
            currentChoose: [],
            data2: [],
            columns2: [
                {
                    title: "选择",
                    key: "id",
                    width: 70,
                    align: "center",
                    render: (h, params) => {
                        // let flag = false;
                        this.data2[params.index] = params.row
                        return h("div", 
                            this.$refs.table.$scopedSlots.flag({
                                    row: params.row,
                                    idx: params.row._index
                                }) 
                        );
                    }
                },
                {
                    title:"排序",
                    key:'isum',
                    align:'center',
                    width:100,
                    render: (h, params) => {
                        let sum = (this.pageNo-1)*this.pageSize + params.index +1;
                        return h("span", sum);
                    }
                },
                {
                    title:"题目类型",
                    key:'questionType',
                    align:'center',
                    render:(h,params) => {
                        let row = params.row;
                        let type = this.followList[row.questionType - 1].name
                        return [
                            h('span', {
                            }, type)
                        ]
                    }
                },
                {
                    title:"题目名称",
                    key:'question',
                    align:'center'
                },
                {
                    title:"设置",
                    align:"center",
                    width:180,
                    render: (h,params) => {
                        let row = params.row;
                        return [
                            h('Button',{
                                style: {
                                    background: "#fff",
                                    color: " #5362e1",
                                    borderRadius: "15px",
                                    border: "1px solid  #5362e1",
                                    width: "60px",
                                    marginRight:"10px"
                                },
                                on: {
                                    click: () => {
                                    this.look(row)                                  
                                    },
                                }
                            },'查看'),
                        ]
                    }
                }
            ],
            formList: [],
            val: '',
            btndisabled: false,
            flag: false
        }
    },
    created() {
        let breadList = [
        { path: "/index", title: "首页" },
        {
            path: "/index/operation/mechanism/index",
            title: "机构运营"
        },
        {
            path: "/index/operation/followForm/index",
            title: "随访表单"
        }
        ];
        this.$emit("changeBreadList", breadList);
    },
    mounted () {       
        this.formId = this.$route.params.id || null
        if(this.formId && this.formId != ''){
            this.title = "编辑"
            this.findFormById(this.pageNo); 
        }              
        this.loadingDepartment();       
        this.searchFormType();       
    },
    methods: {
        handleRowChange(val){
            if(val.flag ==true){
                this.currentChoose.push(val);
            } 
            if(val.flag ==false) {
                this.currentChoose.forEach((i, index) =>{
                    if(i.questionId == val.questionId){
                        this.currentChoose.splice(index,1)
                    }
                })
            }
            this.currentChoose.forEach((item, index)=>{
                item.questionNumber = index+1;
                item.sum = this.addZeros(index);
            })
        },                         
        // 页面查询的科室选择框
        loadingDepartment(){
            let url = api.querydeptname
            let params = {
                hospitalId : this.id
            }
            this.packageAxios(this,url,params,(res)=>{
                // console.log(res);
                if(res.data.success) {
                    let ret = res.data.object;                   
                    this.deptmentList = ret;
                } else {
                    this.$Message.error("加载失败")
                }
            })
        },
        // 查询所有随访表单类型
        searchFormType() {
            let url = api.findSelection
            this.$axios.post(url,{}).then(res => {
                if(res.data.success) {
                    let ret = res.data.object;
                    let aa = []
                    if(ret){
                        ret.forEach(i =>{
                            if(i.name != '健康宣教' && i.name != '宣教科普'){
                                aa.push(i)
                            }
                        })
                    }
                    this.formList = aa
                } else {
                    this.$Message.error("加载关联表单失败")
                }
            })
        },
        lookitem(row){
            this.follow = true
            this.question = row.question
            this.questionType = this.followList[Number(row.questionType) - 1].name
            this.answer = row.answer
            this.answerSelect = row.answerSelect
            this.option = row.sections
            let arr = row.sections
            if(row.questionType == 4){
                this.answer = this.answer.substr(0,this.answer.length - 2)
            }
        },
        //查看问题详情
        look(row){
            this.follow = true
            let params = {
                formId:this.formId,
                id: row.id
            }
            this.$axios.post(api.questionBankById, params).then(res => {
                console.log(res);
                if(res.data.success) {
                    let ret = res.data.object;
                    this.question = ret.question
                    this.questionType = this.followList[Number(ret.questionType) - 1].name
                    this.answer = ret.answer
                    this.answerSelect = ret.answerSelect
                    this.option = ret.sections
                    if(ret.questionType == 4){
                        this.answer = this.answer.substr(0,this.answer.length - 2)
                    }
                } else {
                    let message = res.data.message || res.data.object.file || '查询失败'
                    this.$Message.error(message)
                }
            })
        },
        //关闭题目详情
        cancel(){
            this.follow = false
        },
        // 关闭题目选择弹窗
        cancelAddtitle(){
            this.addtitle = false
        },
        addAnswer (pageNo, flag) {
           this.addtitle = true
           this.currentChoose = this.data1;
            // this.currentChoose.questionNumber = _index+1;
           this.pageNo = pageNo
            let url = api.questionBankPage
            let params = {
                pageNo,
                pageSize: this.pageSize,
                hospitalId: this.id,
                formId: '',
                isUse: 1
            };
            this.$axios.post(url,params).then(res => {
                if(res.data.success) {
                    let ret = res.data.object;
                    this.count = ret.total
                    if(ret){
                        ret.records.forEach((item,index) => {
                            item.questionId = item.id;
                            this.currentChoose.forEach(c =>{
                                if(item.questionId == c.questionId){
                                    item.flag = true;
                                }
                            })
                        })
                    }
                    this.use = Boolean(ret.use);
                    this.data2 = ret.records;
                } else {
                    this.$Message.error("加载随访表单列表失败!")
                }
            })
        },
        pageChange (index) {
            if(this.addtitle){
                this.addAnswer(index, false)
            }
            // this.loadingFollow(index)
        },
        //获取所有题目
        loadingFollow(pageNo) {
            this.pageNo = pageNo 
            let url = api.questionBankPage
            let params = {
                pageNo,
                pageSize: this.pageSize,
                hospitalId: this.id,
                // formId: this.formId
                id: this.formId,
                searchKey: this.val,
                isUse: 1
            };
            this.$axios.post(url,params).then(res => {
                if(res.data.success) {
                    let ret = res.data.object;
                    this.count = ret.total
                    if(ret.records){
                        ret.records.forEach((item,index) => {
                            item.isum = this.addZeros(index)
                        })
                        this.data2 = ret.records;
                    } else {
                        this.data2 = []
                    }                   
                    this.use = Boolean(ret.use);
                } else {
                    this.$Message.error("加载随访表单列表失败!")
                }
            })
        },
        //确认添加选好的题
        add(){
            // this.currentChoose.forEach((item,index) => {
            //     this.data1.push(item)
            // })
            this.addtitle = false
            console.log(this.data1)
            this.data1.forEach((item,index) => {
                // 排序
                item.sum = this.addZeros(index)
                item.questionNumber = index+1;
                if(item.num){
                    this.money()
                }
            })
        },
        handleSubmit (name) {
            this.btndisabled = true
            this.$refs[name].validate((valid) => {
                if (valid) {
                    let url = ''
                    let params = {}
                    params.formName = this.formValidate.formName
                    params.pattern = this.formValidate.pattern
                    params.iused = Number(this.iused)
                    params.qnum = this.data1.length
                    params.hospitalId = this.id
                    params.deptId = this.formValidate.deptId ? this.formValidate.deptId : null;
                    params.contentList = this.data1
                    if(this.formValidate.deptId) {
                        this.deptmentList.forEach(i => {
                        if(this.formValidate.deptId == i.id) {
                                params.deptName = i.deptNickname
                                params.deptType = i.dictType
                            }
                        });
                    } else {
                        params.deptName = null
                        params.deptType = null
                    }                 
                    if(this.data1.length<1) {
                        this.$Message.error('请添加题目')
                        this.btndisabled = false
                        return
                    }
                    let countnum = 0;
                    let numstr = ";";
                    this.data1.forEach(i => {
                       if(!i.questionNumber){
                            countnum++;
                       }
                       if(numstr.indexOf(";"+i.questionNumber+";")!=-1){
                           countnum++;
                       }
                        numstr += i.questionNumber+";";
                    });
                    if(countnum){
                        console.log(this.data1)
                        this.$Message.error('显示顺序不能为空,且不能重复!')
                        this.btndisabled = false
                        return
                    }
                    if(!Boolean(this.formId)){
                        url = api.insertForm
                    } else {
                        url = api.insertForm
                        params.id = this.formId
                    }
                    this.$axios.post(url, params).then(res => {
                        if(res.data.success) {
                            this.handleReset('formValidate')
                            this.$Message.success(res.data.message)
                            this.btndisabled = false
                            this.functionJS.paramsNavgationTo(this,"followFormList", {
                            // 公用方法
                                pageNo: 1
                            }); 
                        } else {
                            this.btndisabled = false
                            this.$Message.error(res.data.message)
                        }
                    })
                } else {
                    this.btndisabled = false
                    this.$Message.error('请完整填写必填项!');
                }
            })
        },
        handleReset (name) {
            this.modalStatus = false;
            this.$refs[name].resetFields();
            this.formValidate.pettern = '';
            this.formValidate.formName = ''
            this.formValidate.id = ''
            this.functionJS.paramsNavgationTo(this,"followFormList", {
            // 公用方法
                pageNo: 1
            }); 
        },
        findFormById(pageNo) {
            let url = api.formById
            let params = {
                pageNo,
                pageSize: this.pageSize,
                hospitalId: this.id,
                // formId: this.formId
                id: this.formId
            };
            this.$axios.post(url,params).then(res => {
                if(res.data.success) {
                    let ret = res.data.object;
                    console.log(ret);
                    this.count = ret.count
                    this.formValidate.formName = ret.formName
                    this.formValidate.pattern = String(ret.pattern)
                    this.formValidate.deptId = ret.deptId
                    if(ret.contentList){
                        this.data1 = ret.contentList
                        this.data1.forEach((item,index) => {
                            // item.questionNumber = index+1;
                            item.sum = this.addZeros(index)
                        })
                    } else {
                        this.data1 = []
                    }
                    this.iused = Boolean(ret.iused);
                } else {
                    this.$Message.error("获取随访表单详情失败!")
                }
            })      
        },
    }
}
</script>
<style lang="less" scoped>
.followEdit{
    width: 100%;
    padding: 10px 0px;
    margin: 0 auto;
    background: #fff;   
    .main {
        width: 98%;
        display: flex;
        flex-direction: column;
        margin: 10px auto;
        border: 1px solid #f0f0f0;
        box-shadow: 0 4px 3px #ebedf8;
        border-radius: 5px;
        margin-bottom: 20px;
        .box{
            padding: 0 40px 20px 40px;
        }
        .title {
            font-size: 20px;
            padding-left: 15px;
            margin-bottom: 20px;
            color: #333;
            height: 40px;
            line-height: 40px;
            background: #ebedf8;         
        }
    }
}
.arr{
    margin-bottom: 10px;
}
.s1{
    font-size: 14px;
    font-weight: 550;
}
.s2{
    font-size: 14px;
}
.ibanner_header {
    width: 100%;
    margin: 0 auto;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    .box {
    display: flex;
    flex-direction: row;
    }
}
</style>
